<template>

    <mi-dialog v-model="areaTree.show" destroy-on-close title="选择城市" width="600px">

        <div>
            <el-tree-v2 ref="treeRef"
                        :data="areaTree.list"
                        :props="{value:'id', label: 'title', children:'children'}"
                        show-checkbox
                        :height="500"></el-tree-v2>
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeTree">取消</el-button>
                <el-button type="primary" @click="areaTreeConfirm">确定</el-button>
            </span>
        </template>

    </mi-dialog>

    <el-form style="width: 100%"
             v-if="edit.info.conditions.length>0"
             ref="regionsFormRef"
             :model="edit.info.conditions"
    >
        <el-scrollbar>
            <table class="mi_table" >
                <thead>
                <tr>
                    <th>区域</th>
                    <th>数量</th>
                    <th>价格</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(vo,i) in edit.info.conditions" :key="vo.id">
                    <!--                <td>-->
                    <!--                    <el-tag size="small" effect="plain" v-for="voo in vo.region" :key="voo.id">{{voo.short_name}}</el-tag>-->
                    <!--                </td>-->
                    <td>
                        <el-space wrap>
                            <div v-for="voo in vo.regionInfoArr">
                                <span>{{voo.title}}</span>
                                <template v-if="voo.children.length>0">
                                    <el-tag size="small" effect="plain" v-for="city in voo.children">
                                        <span>{{city.title}}</span>
                                        <template v-if="city.children.length>0">
                                            (
                                            <span v-for="district in city.children" class="f_secondary">{{district.title}}</span>
                                            )
                                        </template>
                                    </el-tag>
                                </template>
                            </div>
                        </el-space>
                    </td>
                    <td>
                        <el-form-item :prop="i+'.piece'" class="width80" :rules="[{ required: true,  message: '必填' }]">
                            <mi-input-number v-model="vo.piece" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item :prop="i+'.price'" class="width80" :rules="[{ required: true,  message: '必填' }]">
                            <mi-input-number v-model="vo.price" />
                        </el-form-item>
                    </td>
                    <td class="text_center">
                        <el-button link type="primary" @click="delRegion(i)">删除</el-button>
                    </td>
                </tr>
                </tbody>
            </table>
        </el-scrollbar>
    </el-form>

    <el-link type="warning" @click="openTree">为指定区域设置运费</el-link>


</template>

<script setup lang="ts">


import {inject, onBeforeMount, reactive, ref} from "vue";
import area from "@/service/area";
import Edit from "@/model/edit";
import {ElTreeV2, FormInstance} from "element-plus";

const edit = inject<Edit>("edit", new Edit({}))
const areaTree : Record<string, any> = reactive({
    show:false,
    list:[],
    index:-1,
})
const treeRef = ref<InstanceType<typeof ElTreeV2>>()
const regionsFormRef = ref<FormInstance>()

const closeTree = () =>{
    areaTree.show = false
}

const openTree = () => {
    areaTree.show = true
}

const delRegion = (i:number)  => {
    edit.info.conditions.splice(i, 1)
}

const areaTreeConfirm = () => {
    const checked : any[] = treeRef.value?.getCheckedKeys() || []
    // const nodes = treeRef.value?.getCheckedNodes()
    const checkedInfo = getCheckedInfo(areaTree.list, checked)

    if (areaTree.index == -1){  // 添加
        edit.info.conditions.push({
            regionIdArr: checked,
            regionInfoArr: checkedInfo
        })
    }else{  // 编辑
        edit.info.conditions[areaTree.index].regionIdArr = checked
        edit.info.conditions[areaTree.index].regionInfoArr = checkedInfo
    }
    // 关闭弹窗
    closeTree()

}

const getCheckedInfo = (areaList:any[], checkedIds:any[]) => {
    const checkedInfoArr  = new Array()
    for (let li of areaList){
        if (checkedIds.includes(li.id)){    // 选中，加入选中列表中
            checkedInfoArr.push({
                id:li.id,
                title:li.title,
                children:[],
            })
        }else{  // 未选中，查询下级
            const childrenArr = getCheckedInfo(li.children, checkedIds)
            if (childrenArr.length>0){  // 有选中的下级，将当前地区和选中的下级加入到选中列表中
                checkedInfoArr.push({
                    id:li.id,
                    title:li.title,
                    children:childrenArr
                })
            }
        }
    }

    return checkedInfoArr

}

const validate = () => {
    return new Promise((resolve) => {

        //  没有区域运费信息
        if(edit.info.conditions.length==0){
            resolve(true)
        }

        // 有区域运费信息
        regionsFormRef.value?.validate((valid, fields) => {
            if (valid){
                resolve(true)
            }else{
                for(let prop in fields){
                    regionsFormRef.value?.scrollToField(prop)
                    break
                }
                resolve(false)
            }
        })
    })

}

/**
 * 所有地区的树形数组
 */
const getAreas = () => {
    area.getChildrenTree().then(tree => {
        areaTree.list = tree
    })
}

onBeforeMount(() => {
    getAreas()
})

// 暴露属性
defineExpose({
    validate
})

</script>

<style scoped>

</style>
